﻿using System;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using UnityEngine;
using Random = UnityEngine.Random;

namespace NpcFramework
{
    public class CustomPath : RichAI
    {
        public Action onReached;

        // 寻路失败最大重试次数
        public int MaxErrorRetryCount = 5;
        // 寻路失败重试间隔
        int _errorRetryCount = 0;

        protected override void Start () 
        {
            base.Start();
            
            // 打散寻路射线检测的时机
            gravityUpdateDuration = Random.Range(1f, 2f);
        }
        
        public override void OnTargetReached()
        {
            base.OnTargetReached();
            onReached?.Invoke();
        }

        public bool GetPathBuffer(List<Vector3> buffer)
        {
            GetRemainingPath(buffer, out bool stale);
            return stale;
        }


        public override Vector3 GetFeetPosition()
        {
            Vector3 feetPos = base.GetFeetPosition();
            if (feetPos.y > 20)
            {
                UnityEngine.Debug.LogError("寻路容错：" + feetPos, transform.gameObject);
                feetPos.y = 0;
            }
            return feetPos;
        }

        void RetrySearchPath(bool resetErrorRetryCount)
        {
            if (resetErrorRetryCount)
            {
                _errorRetryCount = 0;
            }

            if (_errorRetryCount >= MaxErrorRetryCount)
            {
                return;
            }
            
            _errorRetryCount++;
            this.SearchPath();
        }
        
        protected override void OnPathComplete (Path p) 
        {
            // if (transform.name.Contains("PlayerSeek"))
            // {
            //     UnityEngine.Debug.LogError($"玩家寻路：state:{p.CompleteState}, distance:{this.remainingDistance}, reached:{this.reachedDestination}, path:{p.path.Count}");
            // }
            if (p.CompleteState == PathCompleteState.Error)
            {
                // UnityEngine.Debug.LogError($"寻路Error：node:{transform.parent.name}, state:{p.CompleteState}, distance:{this.remainingDistance}, reached:{this.reachedDestination}, path:{p.path.Count}");
                // 寻路失败
                RetrySearchPath(false);
            }
            else if (p.CompleteState == PathCompleteState.Complete)
            {
                // UnityEngine.Debug.LogError($"寻路Complete：node:{transform.parent.name}, state:{p.CompleteState}, distance:{this.remainingDistance}, reached:{this.reachedDestination}, path:{p.path.Count}");
                if (p.path.Count <= 1)
                {
                    // 寻路失败
                    RetrySearchPath(false);
                }
                else
                {
                    // 寻路成功
                    _errorRetryCount = 0;
                }
            }
            
            base.OnPathComplete(p);
        }
        
    }


}
